package com.amc.common.json;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * JSON解析处理
 *
 * @author ZhangXX
 */
public class JacksonJSON {
    public static final String DEFAULT_FAIL = "\"Parse failed\"";
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final ObjectWriter objectWriter = objectMapper.writerWithDefaultPrettyPrinter();

    // 序列化非空字段
    private static final ObjectMapper objectMapper2 = new ObjectMapper();
    private static final ObjectWriter objectWriter2 = objectMapper2.writerWithDefaultPrettyPrinter();

    static {
        objectMapper2.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }

    public static void marshal(File file, Object value) throws Exception {

        objectWriter.writeValue(file, value);

    }

    public static void marshal(OutputStream os, Object value) throws Exception {

        objectWriter.writeValue(os, value);

    }

    public static String marshal(Object value) throws Exception {
        return objectWriter.writeValueAsString(value);
    }

    public static String marshalNotNull(Object value) {
        try {
            return objectWriter2.writeValueAsString(value);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static byte[] marshalBytes(Object value) throws Exception {

        return objectWriter.writeValueAsBytes(value);

    }

    public static <T> T unmarshal(File file, Class<T> valueType) throws Exception {

        return objectMapper.readValue(file, valueType);

    }

    public static <T> T unmarshal(InputStream is, Class<T> valueType) throws Exception {

        return objectMapper.readValue(is, valueType);

    }

    public static <T> T unmarshal(String str, Class<T> valueType) throws Exception {

        return objectMapper.readValue(str, valueType);

    }

    public static <T> T unmarshal(byte[] bytes, Class<T> valueType) throws Exception {

        if (bytes == null) {
            bytes = new byte[0];
        }
        return objectMapper.readValue(bytes, 0, bytes.length, valueType);

    }
}
